#include "PickRay.h"

namespace lib3dw
{
	PickRay::PickRay()
	{
		
	}
	
	PickRay::~PickRay()
	{
	}
	
	void PickRay::Update(int sx, int sy, int sw, int sh) 
	{
		PickRay ray;
		GLdouble modelview[16], projection[16];
		GLdouble x, y, z;
		GLint viewport[4];

		glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
		glGetDoublev(GL_PROJECTION_MATRIX, projection);
		glGetIntegerv(GL_VIEWPORT, viewport);

		gluUnProject(sx, sh - sy, 0.0, modelview, projection, viewport, &x, &y, &z);
		origin = Vector3((float)x, (float)y, (float)z);
		gluUnProject(sx, sh - sy, 1.0, modelview, projection, viewport, &x, &y, &z);
		direction.x = x - origin.x;
		direction.y = y - origin.y;
		direction.z = z - origin.z;
		direction.normalize();
	}
	
	const Vector3 PickRay::GetOrigin() const
	{
		return origin;
	}
	
	const Vector3 PickRay::GetDirection() const
	{
		return direction;
	}
	
	const Vector3 PickRay::GetInverseDirection() const
	{
		return Vector3(1/direction.x, 1/direction.y, 1/direction.z);
	}
	
	const int PickRay::GetSign0() const 
	{
		return (GetInverseDirection().x < 0);
	}
	
	const int PickRay::GetSign1() const 
	{
		return (GetInverseDirection().y < 0);
	}

	const int PickRay::GetSign2() const
	{
		return (GetInverseDirection().z < 0);
	}
}